//
//  CYRetrievePasswordVController.m
//  CreditAddressBook
//
//  Created by Lee on 15/4/29.
//  Copyright (c) 2015年 Lee. All rights reserved.
//  找回密码

#import "CYRetrievePasswordVController.h"
#import "CYLoginHttpTool.h"
#import "MBProgressHUD+MJ.h"
#import "CYEscape.h"
#import "CYJumpsTool.h"
#import "CYJsonInfo.h"
#import "MJExtension.h"
#import "GCD.h"

static dispatch_source_t _timer;

@interface CYRetrievePasswordVController ()

@property (weak, nonatomic) IBOutlet UITextField *phoneTextField;
@property (weak, nonatomic) IBOutlet UITextField *smsTextField;
@property (weak, nonatomic) IBOutlet UIButton *sendSMSBtn;
@property (weak, nonatomic) IBOutlet UIButton *resetBtn;

@property(nonatomic, strong) GCDTimer *GCDTimer;

@end

@implementation CYRetrievePasswordVController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"找回密码";
    
    self.resetBtn.layer.cornerRadius = 4;
    self.resetBtn.layer.masksToBounds = YES;
}

- (IBAction)sendSMS:(id)sender {
    //检查网络
    [self countdown];
    //检查电话号码是否正确
    NSString *regex = @"^(1[0-9][0-9])\\d{8}$";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    BOOL isPhone = [predicate evaluateWithObject:self.phoneTextField.text];
    if (!isPhone) {
        [MBProgressHUD showError:@"请输入正确的电话号码"];
        return;
    }
    
    //确认网络有连接后发送短信验证码
    [CYLoginHttpTool sendSMSWithPhone:self.phoneTextField.text success:^(id json) {
        CYJsonInfo *jsonInfo = [CYJsonInfo objectWithKeyValues:json];
        if (jsonInfo.isSuccess) {
            [MBProgressHUD showSuccess:jsonInfo.message];
            //显示59秒后重试
//            [self startTime];
           
        }else {
            [MBProgressHUD showError:jsonInfo.message];
        }
    } failure:^(NSError *error) {
        [MBProgressHUD showError:CYServerConnectFailure];
        CYLog(@"服务器链接失败：%@", error);
    }];
}

- (IBAction)changeClick:(id)sender {
    NSString *phone = self.phoneTextField.text;
    [CYLoginHttpTool findPasswordWithPhone:phone andPhoneCode:self.smsTextField.text success:^(id json) {
        CYJsonInfo *jsonInfo = [CYJsonInfo objectWithKeyValues:json];
        if (jsonInfo.isSuccess) {
//           [MBProgressHUD showSuccess:jsonInfo.message];
            CYAlertView(jsonInfo.message);
//            [MBProgressHUD showSuccess:@"密码重置为：123456"];
            
            [self.navigationController popViewControllerAnimated:YES];
//            dispatch_source_cancel(_timer);//关闭倒计时
            [self.GCDTimer destroy];
        }else {
            [MBProgressHUD showError:jsonInfo.message];
        }
        
    } failure:^(NSError *error) {
        [MBProgressHUD showError:CYServerConnectFailure];
        CYLog(@"找回密码服务器链接错误:%@", error);
    }];
}

- (void)startTime {
    __block int timeout = 59; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), 1.0 * NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout <= 0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [self.sendSMSBtn setTitle:@"发送验证码" forState:UIControlStateNormal];
                self.sendSMSBtn.userInteractionEnabled = YES;
            });
        }else{
            //            int minutes = timeout / 60;
            int seconds = timeout % 60;
            NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                CYLog(@"____%@",strTime);
                [self.sendSMSBtn setTitle:[NSString stringWithFormat:@"%@s",strTime] forState:UIControlStateNormal];
                self.sendSMSBtn.userInteractionEnabled = NO;
                
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
}

/**
 *  倒计时
 */
- (void)countdown {
    self.GCDTimer = [[GCDTimer alloc] initInQueue:[GCDQueue mainQueue]];
    
    CYWeakObject(weakself, self);
    __block int time = 59;
    [self.GCDTimer event:^{
        if (time < 1) {
            //设置界面的按钮显示 根据自己需求设置
            [weakself.sendSMSBtn setTitle:@"发送验证码" forState:UIControlStateNormal];
            weakself.sendSMSBtn.userInteractionEnabled = YES;
            weakself.sendSMSBtn.backgroundColor = CYColor(79, 118, 245, 1);
            [weakself.GCDTimer destroy];
        } else {
            //        NSLog(@"time:%d", time);
            [weakself.sendSMSBtn setTitle:[NSString stringWithFormat:@"%ds",time] forState:UIControlStateNormal];
            weakself.sendSMSBtn.userInteractionEnabled = NO;
            weakself.sendSMSBtn.backgroundColor = [UIColor grayColor];
        }
        time--;
    } timeInterval:NSEC_PER_SEC * 1];
    [self.GCDTimer start];
}

/**
 *  屏幕点击时触发
 */
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    //    CYLog(@"点击屏幕");
    [self.view.window endEditing:YES];
}

- (void)dealloc {
    CYLog(@"找回密码销毁");
//    dispatch_source_cancel(_timer);
}
@end
